//
//  MediaEditAddrViewController.m
//  XPhoto
//
//  Created by baboy on 2019/5/7.
//  Copyright © 2019 baboy. All rights reserved.
//

#import "AddrSearchViewController.h"
#import <MapKit/MapKit.h>
#import "UIScrollView+x.h"

@interface AddrSearchViewController ()<CLLocationManagerDelegate, MKMapViewDelegate, UITableViewDelegate, UITableViewDataSource,UISearchBarDelegate,BKTableViewDelegate,AddrSearchDelegate>
@property(nonatomic, strong) UISearchController *searchController;
@property(nonatomic, strong) AddrSearchResultsViewController *searchResultsController;

@property(nonatomic, strong) CLLocationManager *locationManager;
@property(nonatomic, strong) CLGeocoder *geocoder;
@property(nonatomic, strong) NSMutableArray *places;
@property(nonatomic, assign) NSInteger page;
@property(nonatomic, strong) NSString *keyword;
@property(nonatomic, strong) NSIndexPath *selectedIndexPath;
@end

@implementation AddrSearchViewController

- (id)init{
    if (self = [super initWithNibName:NSStringFromClass([self class]) bundle:nil]) {
        self.page = 1;
    }
    return self;
}
- (CLLocationManager *)locationManager{
    if (!_locationManager) {
        _locationManager = [[CLLocationManager alloc] init];
        _locationManager.delegate = self;
        _locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers;
        _locationManager.distanceFilter = 10.0f;
        [_locationManager requestWhenInUseAuthorization];
    }
    return _locationManager;
}
- (CLGeocoder *)geocoder{
    if (!_geocoder) {
        _geocoder = [[CLGeocoder alloc] init];
    }
    return _geocoder;
}

- (UISearchController*)searchController{
    if (!_searchController) {
        _searchResultsController = [AddrSearchResultsViewController new];
        _searchResultsController.delegate = self;
        _searchController = [[UISearchController alloc] initWithSearchResultsController:_searchResultsController];
//        _searchController.searchResultsUpdater = self;
        
        //        _searchController.hidesNavigationBarDuringPresentation=YES;
        _searchController.dimsBackgroundDuringPresentation = YES;
        _searchController.searchBar.placeholder = NSLocalizedString(@"search", @"按钮");
        _searchController.searchBar.delegate = self;
        _searchController.searchBar.returnKeyType = UIReturnKeySearch;
    }
    return _searchController;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
//    self.definesPresentationContext = YES;
//    self.edgesForExtendedLayout = UIRectEdgeNone;
//    self.tableView.tableFooterView = [UIView new];
//    self.tableView.tableHeaderView.backgroundColor = [UIColor blueColor];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"cancel", @"按钮") style:UIBarButtonItemStylePlain target:self action:@selector(cancel:)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"done", @"按钮") style:UIBarButtonItemStylePlain target:self action:@selector(done:)];
    self.searchBar.hidden = YES;
    self.tableView.tableHeaderView = self.searchController.searchBar;
    
    if (self.location) {
        self.searchResultsController.location = self.location;
        [self search];
    }else{
        [self.locationManager startUpdatingLocation];
    }
    
    // Do any additional setup after loading the view from its nib.
}
- (void)cancel:(id)button{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
- (void)dismissWithSelectedPlace:(BKPlace*)place{
    
    if(self.delegate && [self.delegate respondsToSelector:@selector(addrSearchViewController:didSelectPlace:)]){
        [self.delegate addrSearchViewController:self didSelectPlace:place];
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)done:(id)button{
    BKPlace *currentPlace = nil;
    if (self.selectedIndexPath) {
        currentPlace = [self.places objectAtIndex:self.selectedIndexPath.row];
    }
    [self dismissWithSelectedPlace:currentPlace];
}
- (void)search{
    CLLocationCoordinate2D coordinate = self.location.coordinate;
    NSString *loc = [NSString stringWithFormat:@"%f,%f",coordinate.longitude, coordinate.latitude];
    [BKPlace search:self.keyword
       withLocation:loc
             radius:30000
               page:self.page
           callback:^(id task, id places, NSError * error) {
        DLOG(@"error:%@",error);
        if (self.page == 1) {
           self.places = [NSMutableArray array];
        }
        if (places) {
           [self.places addObjectsFromArray:places];
           [self.tableView reloadData];
           if (self.places.count>=20) {
               self.tableView.loadMore = YES;
           }
        }
        [self.tableView stopRefreshing];
        [self.tableView stopLoading];
    }];
    
//    [self.geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
//        DLOG(@"%@",placemarks);
//    }];
}
#pragma LocationManager delegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    CLLocation *location = [locations objectAtIndex:0];
    CLLocationCoordinate2D coordinate = location.coordinate;
    self.location = location;
    self.searchResultsController.location = location;
    [self search];
    
    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(coordinate,100, 100);
    MKLocalSearchRequest *request = [[MKLocalSearchRequest alloc]init];
    request.region = region;
    request.naturalLanguageQuery = @"Restaurants";
    MKLocalSearch *localSearch = [[MKLocalSearch alloc]initWithRequest:request];
    [localSearch startWithCompletionHandler:^(MKLocalSearchResponse *response, NSError *error){
        if (!error) {
            DLOG(@"error:%@",error);
        }else{
            //do something.
            DLOG(@"response:%@",response);
        }
    }];
}


#pragma tableview delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSInteger n = self.places.count;
    return n;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CELL_REUSE_ID = @"ADDR_TABLE_CELL_ID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CELL_REUSE_ID];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CELL_REUSE_ID];
    }
    UIView *accessoryView = nil;
    if (self.selectedIndexPath && self.selectedIndexPath.row == indexPath.row) {
        accessoryView = [UIButton buttonWithType:UIButtonTypeContactAdd];
    }
    cell.accessoryView = accessoryView;
    BKPlace *place = [self.places objectAtIndex:indexPath.row];
    cell.textLabel.text = place.name;
    cell.detailTextLabel.text = place.addr;
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.selectedIndexPath) {
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:self.selectedIndexPath];
        cell.accessoryView = nil;
    }
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.accessoryView = [UIButton buttonWithType:UIButtonTypeContactAdd];
    self.selectedIndexPath = indexPath;
    
}
- (void)scrollViewWillBeginLoadingMore:(BKTableView *)tableView{
    self.page += 1;
    [self search];
}
#pragma UISearchBar delegate
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    [searchBar setShowsCancelButton:YES animated:YES];
    return YES;
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    NSString *keyword = [searchBar.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    self.searchResultsController.keyword = keyword;
}
-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    searchBar.text = nil;
    [searchBar setShowsCancelButton:NO animated:YES];
    [self.searchController.searchBar resignFirstResponder];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [self.searchController.searchBar resignFirstResponder];
}

- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    self.edgesForExtendedLayout = UIRectEdgeNone;
}
- (void)addrSearchViewController:(id)vc didSelectPlace:(BKPlace*)place{
    [vc dismissViewControllerAnimated:YES completion:nil];
    [self dismissWithSelectedPlace:place];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
